import React, { useState, useEffect } from 'react'
import {
  Table,
  Input,
  Button,
  Modal,
  Form,
  Popconfirm,
  message,
  DatePicker,
  Select,
} from 'antd'
import '../style/user.scss'
import {
  PlusOutlined,
} from '@ant-design/icons'
import moment from 'moment'
import baseApi from '../api/base'
import withRouter from '../hooks/withRouter'
import { useSelector, useDispatch } from 'react-redux'

const { Search, TextArea  } = Input

function User (props) {
  const columns = [
    {
      title: '姓名',
      dataIndex: 'username',
      key: 'username',
      ellipsis: true,
    },
    {
      title: '账号',
      dataIndex: 'account',
      key: 'account',
      ellipsis: true,
    },
    {
      title: '密码',
      dataIndex: 'password',
      key: 'password',
      ellipsis: true,
      render: (text, r) => {
        return text ? text.replace(/\S/g, '*') : ''
      }
    },
    {
      title: '生日',
      dataIndex: 'birthday',
      key: 'birthday',
      ellipsis: true,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      ellipsis: true,
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      key: 'remarks',
      ellipsis: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updatetime',
      key: 'updatetime',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 150,
      render: (_, r) => {
        if (r.id !== userInfo.id && userInfo.isadmin !== 1) return ''
        return (
        <div className='wrap_operate'>
          <Button type="link" onClick={() => onEdit(r)}>编辑</Button>
          {
            userInfo.isadmin === 1 && r.id !== userInfo.id &&
            <Popconfirm
              title="确认删除此条数据吗？"
              onConfirm={() => onDel(r)}>
              <Button danger type="link">删除</Button>
            </Popconfirm>
          }
        </div>
        )
      }
    },
  ]
  const [form] = Form.useForm()
  const userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
  const [loading, setLoading] = useState(false)
  const [tableData, setTableData] = useState([])
  const [isModalVisible, setIsModalVisible] = useState(false)
  const sexList = useSelector((state) => state.dic.sexList)
  const [operateType, setOperateType] = useState('add')
  const [operateRow, setOperateRow] = useState({})
  const [searchValue, setSearchValue] = useState('')
  const [confirmLoading, setConfirmLoading] = useState(false)

  useEffect(() => {
    // 模拟componentDidMount，即只运行一次该函数
    fetchData()
  }, [])

  const fetchData = () => {
    setLoading(true)
    const model = {
      username: searchValue
    }
    baseApi.findUser(model).then(res => {
      setTableData(res.result)
    }).finally(() => {
      setLoading(false)
    })
  }

  const onChange = (e) =>  {
    setSearchValue(e.target.value)
  }

  const onAdd = () =>  {
    setOperateType('add')
    setIsModalVisible(true)
  }

  const handleOk = () =>  {
    form.validateFields().then(v => {
      setConfirmLoading(true)
      const obj = {
        ...form.getFieldsValue()
      }
      obj.birthday = obj.birthday ? moment(obj.birthday).format('YYYY-MM-DD') : null
      if (operateType === 'add') {
        baseApi.addUser(obj).then(res => {
          message.success('添加成功')
          setIsModalVisible(false)
          fetchData()
        }).finally(() => {
          setConfirmLoading(false)
        })
      } else {
        obj.id = operateRow.id
        baseApi.updateUser(obj).then(res => {
          message.success('编辑成功')
          setIsModalVisible(false)
          fetchData()
        }).finally(() => {
          setConfirmLoading(false)
        })
      }
    })
  }

  const handleCancel = () =>  {
    form.resetFields()
    setIsModalVisible(false)
  }

  const onEdit = (r) =>  {
    const o = JSON.parse(JSON.stringify(r))
    o.birthday = r.birthday ? moment(r.birthday) : null
    o.upDate = r.upDate ? moment(r.upDate) : null
    setOperateType('edit')
    setIsModalVisible(true)
    setOperateRow(o)
    setTimeout(() => {
      form.setFieldsValue(o)
    }, 50);
  }

  const onDel = (r) =>  {
    baseApi.delUser({ id: r.id }).then(res => {
      message.success('删除成功')
      fetchData()
    }) 
  }

  return (
    <div className="con">
      <div className="wrap_search">
        <Search
          placeholder="输入名称搜索..." 
          enterButton
          value={searchValue}
          onChange={e => onChange(e)}
          onSearch={(v) => fetchData()} />
          {
            userInfo.isadmin === 1 && 
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => onAdd()}>新增</Button>
          }
      </div>
      <div className="wrap_table mt--10">
        <Table
          bordered
          loading={loading}
          scroll={{ y: 550 }}
          columns={columns}
          rowKey={(r) => r.id}
          dataSource={tableData} />
      </div>

      <Modal
        title={operateType === 'add' ? '新增用户' : '编辑用户'}
        visible={isModalVisible}
        destroyOnClose
        confirmLoading={confirmLoading}
        onOk={() => handleOk()}
        onCancel={() => handleCancel()}>
        <div>
        <Form
          name="form"
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}>
          <Form.Item
            label="姓名"
            name="username"
            rules={[
              {
                required: true,
                message: '请输入姓名',
              },
            ]}>
            <Input />
          </Form.Item>
          <Form.Item
            label="账号"
            name="account"
            type="number"
            rules={[
              {
                required: true,
                message: '请输入账号',
              },
            ]}>
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码',
              },
            ]}>
            <Input />
          </Form.Item>
          <Form.Item
            label="生日"
            name="birthday">
            <DatePicker />
          </Form.Item>
          <Form.Item
            label="性别"
            name="sex">
            <Select allowClear options={sexList}></Select>
          </Form.Item>
          <Form.Item
            label="备注"
            name="remarks">
            <TextArea rows={4}/>
          </Form.Item>
        </Form>
        </div>
      </Modal>
    </div>
  )
}

export default withRouter(User)

